package com.baichang.taoshunda.service.impl;

import com.baichang.taoshunda.dao.GoodsTypeDao;
import com.baichang.taoshunda.dao.ParamsDao;
import com.baichang.taoshunda.entity.GoodsType;
import com.baichang.taoshunda.service.GoodsService;
import com.baichang.taoshunda.service.GoodsTypeService;
import com.baichang.taoshunda.utils.ConvertTypeUtils;
import com.baichang.framework.excelption.ServiceException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class GoodsTypeServiceImpl implements GoodsTypeService {

    @Autowired
    private GoodsTypeDao goodsTypeDao;
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ParamsDao paramsDao;

    @Override
    public List<Map<String, Object>> findCompanyGoodsType(Integer companyId) {
        List<Map<String, Object>> list = goodsTypeDao.findCompanyGoodsType(companyId);
        int id = 37;
        Map<String, Object> map = paramsDao.queryParams(id);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("videoMoney",map.get("videoMoney"));
        }
        return list;
    }

    @Override
    public boolean addGoodsType(Integer bussId, String name, Integer orderNumber) {
        GoodsType goodsType = new GoodsType();
        goodsType.setName(name);
        goodsType.setOrderNum(orderNumber);
        goodsType.setCompanyId(bussId);
        return goodsTypeDao.save(goodsType) > 0;
    }

    @Override
    public boolean updateGoodsType(Integer id, String name, Integer orderNumber) {
        return goodsTypeDao.updateGoodsType(id, name, orderNumber);
    }

    @Override
    public boolean deleteGoodsType(Integer id) throws ServiceException {
        int goodsCount = goodsService.getGoodsCountByGoodsTypeId(id);
        if (goodsCount == 0) {
            return goodsTypeDao.deleteById(id) > 0;
        }
        throw new ServiceException("请优先删除该分类下的商品");
    }

    /**
     * 修改商品类别排序
     *
     * @param jsonData
     * @return
     */
    @Override
    public boolean updateGoodsTypeOrderNum(String jsonData) {
        JSONArray jsonArray = JSONArray.fromObject(jsonData);
        boolean flag = false;
        if (jsonArray != null && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String, Object> map = (Map<String, Object>) jsonArray.get(i);
                Integer typeId = ConvertTypeUtils.obj2Integer(map.get("id"));
                Integer orderNumber = ConvertTypeUtils.obj2Integer(map.get("orderNumber"));
                flag = goodsTypeDao.updateGoodsTypeOrderNumber(typeId, orderNumber) > 0;
            }
        }
        return flag;
    }
}
